package com.example.client.config;

import com.example.common.codec.NettyMessage;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author: 582895699@qq.com
 * @Desctription: TODO
 * @Date: Created in 2021/11/28 23:10
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接已关闭");
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        // 空闲时，向服务端发起一次心跳
//        if (event instanceof IdleStateEvent) {
//            log.info("[userEventTriggered][发起一次心跳]");
//            NettyMessage nettyMessage = new NettyMessage("Heartbeat", "HeartbeatResponse");
//            ctx.writeAndFlush(nettyMessage)
//                    .addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
//        } else {
//            super.userEventTriggered(ctx, event);
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        if (cause instanceof ReadTimeoutException) {
            log.info("客户端连接超时；channelId:{}", channel.id());
            channel.close();
            return;
        }
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        log.info("收到客户端响应;msg:{}", msg);
    }
}
